package com.kfm.listener;

import com.kfm.util.Contains;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebListener
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        InputStream resourceAsStream = MyServletContextListener.class.getClassLoader().getResourceAsStream("config.properties");

        Properties prop = new Properties();

        try {
            prop.load(resourceAsStream);

            String title = prop.getProperty("title");
            servletContext.setAttribute("app_title", title);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // mybatis
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
            servletContext.setAttribute(Contains.SQL_SESSION_FACTORY, sqlSessionFactory);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
